package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.PlaceSupplyOrderEntity;
import com.shaoshaohuo.app.entity.PoiEntity;
import com.shaoshaohuo.app.entity.post.SupplyOrderAdd;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.PoiEntityUtils;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.text.DecimalFormat;

/**
 * @ClassName BuysGoodsActivity
 * @author linmu
 * @Decription 我要买货-
 * @2015-8-30 下午5:48:00
 */
public class BuysGoodsTargetActivity extends BaseActivity implements OnClickListener {

	private TopbarView mTopbarView;

	// private MeasureGridView mPinzhongGv;
	// private MeasureGridView mOneWeightGv;
	// private MeasureGridView mGuaxingGv;

	private EditText mProductEdit;
	private EditText mBuyCountEdit;
	private TextView mBuyUnitText;
	// private View mBuyUnitLayout;
	// private View mStartTimeLayout;
	// private TextView mStartTimeText;
	// private View mEndTimeLayout;
	// private TextView mEndTimeText;
	private View mRecivAddressLayout;
	private TextView mRecivAddressText;
	private TextView mDetailAddressText;
	private EditText mContactNameEdit;
	private EditText mContactPhoneEdit;
	private EditText mBuyYaoqiuEdit;

	private TextView mPriceUnitText;
	
	private EditText mBuyPriceEdit;
	// private CheckBox mShuaihuoCb;
	// private EditText mQidingxianzhiEdit;
	private TextView mTotalText;

	private Button mNextButton;

	private String supplyid;
	private String productName;
	private String price;
	private String unit;
	private CascadingMenuPopWindow cascadingMenuPopWindow;
	private double totalPrice = 0;

	private PoiEntity startPoi;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(new TopbarView(this));
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				setContentView(R.layout.activity_buy_goods_target);
				initData();
				initView();
				setUpView();
			}
		}, 200);

	}

	protected void initData() {
		Intent intent = getIntent();
		supplyid = intent.getStringExtra(ExtraName.id);
		productName = intent.getStringExtra(ExtraName.productName);
		price = intent.getStringExtra(ExtraName.price);
		unit = intent.getStringExtra(ExtraName.unit);
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		// mPinzhongGv = (MeasureGridView) this.findViewById(R.id.gv_pinzhong);
		// mOneWeightGv = (MeasureGridView)
		// this.findViewById(R.id.gv_one_weight);
		// mGuaxingGv = (MeasureGridView) this.findViewById(R.id.gv_guaxing);

		mProductEdit = (EditText) this.findViewById(R.id.edittext_product);
		mBuyCountEdit = (EditText) this.findViewById(R.id.edittext_buy_count);
		mBuyUnitText = (TextView) this.findViewById(R.id.textview_buy_unit);
		// mBuyUnitLayout = this.findViewById(R.id.layout_buy_unit);
		// mStartTimeLayout = this.findViewById(R.id.layout_start_time);
		// mStartTimeText = (TextView)
		// this.findViewById(R.id.textview_start_time);
		// mEndTimeLayout = this.findViewById(R.id.layout_end_time);
		// mEndTimeText = (TextView) this.findViewById(R.id.textview_end_time);
		mRecivAddressLayout = this.findViewById(R.id.layout_recev_address);
		mRecivAddressText = (TextView) this.findViewById(R.id.textview_recev_address);
		mDetailAddressText = (TextView) this.findViewById(R.id.textview_recev_address_detail);
		mContactNameEdit = (EditText) this.findViewById(R.id.textview_contact_name);
		mContactPhoneEdit = (EditText) this.findViewById(R.id.textview_contact_phone);
		mBuyYaoqiuEdit = (EditText) this.findViewById(R.id.edittext_buy_yaoqiu);

		mBuyPriceEdit = (EditText) this.findViewById(R.id.edittext_buy_price);
		// mShuaihuoCb = (CheckBox) this.findViewById(R.id.cb_shuaihuo);
		// mQidingxianzhiEdit = (EditText)
		// this.findViewById(R.id.edittext_qidingxianzhi);

		mPriceUnitText = (TextView) this.findViewById(R.id.textview_price_unit);
		
		mTotalText = (TextView) this.findViewById(R.id.textview_total);

		mNextButton = (Button) this.findViewById(R.id.button_next);
	}

	private void setUpView() {
		mTopbarView.setCenterText("我要买货");
		mTopbarView.setLeftView(true, true);

		mProductEdit.setText(productName);
		mBuyPriceEdit.setText(price);
		mBuyUnitText.setText(unit);
		mPriceUnitText.setText("元/"+unit);

		// List<String> list = new ArrayList<>();
		// list.add("");
		// list.add("");
		// list.add("");
		// list.add("");
		//
		// ProductGridviewAdapter<String> adapter = new
		// ProductGridviewAdapter<>(this, list, false);
		// mPinzhongGv.setAdapter(adapter);
		// mOneWeightGv.setAdapter(adapter);
		// mGuaxingGv.setAdapter(adapter);
		//
		// mBuyUnitLayout.setOnClickListener(this);
		// mStartTimeLayout.setOnClickListener(this);
		// mEndTimeLayout.setOnClickListener(this);
		mRecivAddressLayout.setOnClickListener(this);
		mNextButton.setOnClickListener(this);

		mBuyCountEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				String num = mBuyCountEdit.getText().toString().trim();
				if(TextUtils.isEmpty(num)){
				    totalPrice = 0;
				    mTotalText.setText("总价：￥" + 0);
				}else{
				    int numInt = Integer.parseInt(num);
				    totalPrice = numInt * Double.parseDouble(price);
				    mTotalText.setText("总价：￥" + new DecimalFormat(",###.00").format(totalPrice));
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
	    DeviceHelper.hideIME(mTopbarView);
		switch (v.getId()) {
		// case R.id.layout_buy_unit:
		//
		// break;
		// case R.id.layout_start_time:
		//
		// break;
		// case R.id.layout_end_time:
		//
		// break;
		case R.id.layout_recev_address:
			selectAddressPoi();
			break;
		case R.id.button_next:
			// showToast("去支付");
			placeOrder();
			break;
		}
	}

	private void selectAddressPoi() {
		if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this, false);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mRecivAddressText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mRecivAddressText, 5, 5);
		}
	}
	// 级联菜单选择回调接口
	 	class NMCascadingMenuViewOnSelectListener implements
	 			CascadingMenuViewOnSelectListener {

	 		@Override
	 		public void getValue(Area city, String fullname) {
	 			mRecivAddressText.setText(fullname);
	 			startPoi = PoiEntityUtils.convert(city, fullname);
	 		}

	 	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			startPoi = (PoiEntity) data.getSerializableExtra(ExtraName.poi);
			mRecivAddressText.setText(startPoi.getTitle());
		}
	}

	private void placeOrder() {
		SupplyOrderAdd supplyOrder = new SupplyOrderAdd();

		String num = mBuyCountEdit.getText().toString().trim();
		if (TextUtils.isEmpty(num)) {
			showToast("请输入购买数量");
			return;
		}

		if (startPoi == null) {
			showToast("请选择收货地址");
			return;
		}

		String address = mDetailAddressText.getText().toString().trim();
		if (TextUtils.isEmpty(address)) {
			showToast("请输入详细地址");
			return;
		}

		String realname = mContactNameEdit.getText().toString().trim();
		String mobile = mContactPhoneEdit.getText().toString().trim();
		if (TextUtils.isEmpty(realname)) {
			showToast("请输入联系人姓名");
			return;
		}
		if (TextUtils.isEmpty(mobile)) {
			showToast("请输入联系人电话");
			return;
		}
		if (!StringHelper.isPhoneNumber(mobile)) {
			showToast("请输入合格的联系人电话");
			return;
		}

		String receivecitycode = startPoi.getId();
		String receivelng = startPoi.getLng() + "";
		String receivelat = startPoi.getLat() + "";

		supplyOrder.setSupplyid(supplyid);
		supplyOrder.setNum(num);
		supplyOrder.setReceivecontact(realname);
		supplyOrder.setRecemobile(mobile);
		supplyOrder.setReceiveaddress(mRecivAddressText.getText().toString() + address);
		supplyOrder.setReceivecityid(receivecitycode);
		supplyOrder.setReceivelng(receivelng);
		supplyOrder.setReceivelat(receivelat);
		// supplyOrder.setReceivetime("2015-09-09");

		startLoadingDialog();
		RequestService.getInstance().addSupplyOrder(this, supplyOrder, PlaceSupplyOrderEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					PlaceSupplyOrderEntity entity = (PlaceSupplyOrderEntity) resultData;
					Intent intent = new Intent(BuysGoodsTargetActivity.this, PayEcActivity.class);
					intent.putExtra(ExtraName.orderid, entity.getData().getOrderid());
					intent.putExtra(ExtraName.totalPrice, totalPrice);
					intent.putExtra(ExtraName.action, PayEcActivity.PAY_ACTION_SUPPLY);
					startActivity(intent);
				} else {
					// PlaceSupplyOrderEntity entity = (PlaceSupplyOrderEntity)
					// resultData;
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}
	@Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}
}
